<?php
/**
 * 人人网第三方登录驱动
 */
namespace mcOAuth\Driver;
class renren extends \mcOAuth\OAuth{
    protected $API_URL = 'https://graph.renren.com/';

    /**
     * 生成获取AuthorizeCode地址
     * @return url
     */
    protected function buildAuthorizeCodeURL(){
        $params=array(
            'response_type' =>'code',
            'client_id'     =>$this->config['APP_KEY'],
            'redirect_uri'  =>$this->config['callback'],
            'scope'         =>$this->config['scope'],
            'display'       =>$this->config['display'],
        );
        $url=$this->buildAPI('oauth/authorize',$params);
        return $url;
    }

    /**
     * 获取AccessToken
     */
    protected function doGetAccessToken(){
        $params = array(
            'grant_type'    =>'authorization_code',
            'client_id'     =>$this->config['APP_KEY'],
            'client_secret' =>$this->config['SECRET_KEY'],
            'code'          =>$this->AuthorizeCode,
            'redirect_uri'  =>$this->config['callback'],
        );
        $result=$this->requestAPI('oauth/token',$params,'POST');
        if(!empty($result)){
            $data=json_decode($result,true);
            return $this->setAccessTokenAttr($data);
        }else{
            exception($result);
        }
    }

    /**
     * 格式化获取的AccessToken数据
     */
    protected function setAccessTokenAttr($data){
        $this->AccessToken=$data['access_token'];
        $this->OpenID=$data['user']['id'];
        $this->UserInfo=$data['user'];
        $params = array(
            'access_token'  => $data['access_token'],
            'expires_in'    => $data['expires_in'],
            'refresh_token' => $data['refresh_token'],
            'openid'        => $data['user']['id'],
            'create_at'     => time()
        );
        return $params;
    }

    /**
     * 获取OpenID
     */
    protected function doGetOpenID(){
        return $this->OpenID;
    }

    /**
     * 格式化获取的OpenID数据
     */
    protected function setOpenIDAttr($data){
    }

    /**
     * 获取用户信息
     */
    protected function doGetUserInfo(){
        if(!empty($this->UserInfo)){
            $data=$this->setUserInfoAttr($this->UserInfo);
            return $data;
        }else{
            exception('获取UserInfo失败，请重试！');
        }
    }

    /**
     * 格式化获取的用户信息数据
     */
    protected function setUserInfoAttr($data){
        $params = array(
            'openid'  => $this->OpenID,
            'channel' => $this->config['channel'],
            'nickname'=> $data['name'],
            'gender'  => 'n',
            'avatar'  => $data['avatar'][2]['url']
        );
        return $params;
    }
}
